package com.yc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.R_Code;
import com.yc.Result;
import com.yc.entities.BloodSugarBed;
import com.yc.entities.BloodSugarPatientInfo;
import com.yc.entities.custom.CustomSaveBedRequestBean;
import com.yc.service.BloodSugarBedService;
import com.yc.service.BloodSugarPatientInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 院内床位信息表 前端控制器
 * </p>
 *
 * @author kuakha
 * @since 2021-04-07
 */
@RestController
@Slf4j
@RequestMapping("/bloodSugarBed")
@Api(value = "BloodSugarBedController", tags = {"床位信息管理"})
public class BloodSugarBedController {

    @Autowired
    private BloodSugarBedService bloodSugarBedService;

    @Autowired
    private BloodSugarPatientInfoService bloodSugarPatientInfoService;

    @ApiOperation(value = "pc查询床位信息")
    @PreAuthorize("hasAnyAuthority('sys:bedManage','sys:noAccess')")
    @GetMapping("getBedInfo")
    public Result getBedInfo(@ApiParam(name = "deanId", value = "院长id") @RequestParam Integer deanId,
                             @ApiParam(name = "departmentId", value = "科室id") @RequestParam(required = false) Integer departmentId,
                             @ApiParam(name = "current", value = "当前页码") @RequestParam(required = false) Integer current,
                             @ApiParam(name = "size", value = "一页显示多少条") @RequestParam(required = false) Integer size) {
        return bloodSugarBedService.getBedInfo(deanId,departmentId,current,size);
//        LambdaQueryWrapper<BloodSugarBed> bedLambdaQueryWrapper = Wrappers.lambdaQuery();
//        bedLambdaQueryWrapper.eq(BloodSugarBed::getDeanId, deanId);
//        bedLambdaQueryWrapper.orderByAsc(BloodSugarBed::getBedNum);
//        if (departmentId != null) {
//            bedLambdaQueryWrapper.eq(BloodSugarBed::getDepartmentId, departmentId);
//        }
//        Page<BloodSugarBed> sugarBedPage = new Page<>(current == null ? 0 : current, size == null ? 10 : size);
//        IPage<BloodSugarBed> sugarDepartmentPage = bloodSugarBedService.page(sugarBedPage, bedLambdaQueryWrapper);
//        if (sugarBedPage.getTotal() > 0) {
//            return Result.ok().data(sugarDepartmentPage.getRecords()).total((int) sugarBedPage.getTotal());
//        } else {
//            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
//        }
    }

    @ApiOperation(value = "pc添加床位信息")
    @PreAuthorize("hasAnyAuthority('sys:bedManage','sys:noAccess')")
    @PostMapping("addBedInfo")
    @Transactional(rollbackFor = Exception.class)
    public Result addBedInfo(@Valid @RequestBody CustomSaveBedRequestBean customSaveBedRequestBean) {
        LambdaQueryWrapper<BloodSugarBed> bedLambdaQueryWrapper = Wrappers.lambdaQuery();
        bedLambdaQueryWrapper.eq(BloodSugarBed::getDeanId, customSaveBedRequestBean.getDeanId());
        bedLambdaQueryWrapper.eq(BloodSugarBed::getDepartmentId, customSaveBedRequestBean.getDepartmentId());
        //已有的床位
        List<BloodSugarBed> list = bloodSugarBedService.list(bedLambdaQueryWrapper);
        List<Integer> dbList = new ArrayList<>();
        if (list.size() > 0) {
            list.forEach(bloodSugarBed -> {
                dbList.add(bloodSugarBed.getBedNum());
            });
        }
        //要添加到数据库的床位数据
        Collection<BloodSugarBed> bloodSugarBedList = new ArrayList<>();
        // 生成床位 排除数据库已经存在的床位
        IntStream.rangeClosed(customSaveBedRequestBean.getStartBedNumber(), customSaveBedRequestBean.getEndBedNumber()).forEach(bedNum -> {
            bloodSugarBedList.add(new BloodSugarBed()
                    .setBedNum(bedNum)
                    .setDepartmentId(customSaveBedRequestBean.getDepartmentId())
                    .setDeanId(customSaveBedRequestBean.getDeanId()));
        });
        List<BloodSugarBed> collect = bloodSugarBedList.stream().filter(bloodSugarBed -> !dbList.contains(bloodSugarBed.getBedNum())).collect(Collectors.toList());
        boolean b = bloodSugarBedService.saveBatch(collect);
        if (b) {
            return Result.ok();
        }
        return Result.error().code(R_Code.R_ADD_FAIL);
    }


    @ApiOperation(value = "pc删除床位信息")
    @PreAuthorize("hasAnyAuthority('sys:bedManage','sys:noAccess')")
    @GetMapping("deleteBedInfo/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result deleteBedInfo(@ApiParam(name = "id", value = "床位id") @NotNull(message = "床位id不能为空") @PathVariable Integer id) {
        BloodSugarBed bloodSugarBed = bloodSugarBedService.getById(id);
        if (bloodSugarBed != null) {
            if (!bloodSugarBed.getUserId().equals(0)){
                return Result.error().code(R_Code.R_DELETE_FAIL).message("改床位上有患者,请出院或者转移床位");
            }
        }
        boolean b = bloodSugarBedService.removeById(id);
        if (b) {
            return Result.ok();
        }
        return Result.error().code(R_Code.R_DELETE_FAIL);
    }


    @ApiOperation(value = "APP查询床位信息")
    @PostMapping(value = "getAllBedByDeanIdAndDepartmentId")
    public Result getAllBedByDeanIdAndDepartmentId(@ApiParam(name = "deanId", value = "院长id") @RequestParam(value = "deanId")String deanId,
                             @ApiParam(name = "departmentId", value = "科室id") @RequestParam(value = "departmentId")String departmentId,
                             @ApiParam(name = "current", value = "当前页码") @RequestParam(defaultValue = "1",required = false) Integer current,
                             @ApiParam(name = "size", value = "一页显示多少条")@RequestParam(defaultValue = "10",required = false)Integer size) {
        if (StringUtils.isEmpty(deanId)){
            return Result.error().message("院长id不能为空").code(301);
        }
        if (StringUtils.isEmpty(departmentId) || "-1".equals(departmentId)){
            return Result.error().message("科室id不能为空").code(302);
        }
        LambdaQueryWrapper<BloodSugarBed> bedLambdaQueryWrapper = Wrappers.lambdaQuery();
        bedLambdaQueryWrapper.eq(BloodSugarBed::getDeanId, deanId);
        bedLambdaQueryWrapper.orderByAsc(BloodSugarBed::getBedNum);
        bedLambdaQueryWrapper.eq(BloodSugarBed::getDepartmentId, departmentId);
        Page<BloodSugarBed> sugarBedPage = new Page<>(current == null ? 0 : current, size == null ? 10 : size);
        IPage<BloodSugarBed> sugarDepartmentPage = bloodSugarBedService.page(sugarBedPage, bedLambdaQueryWrapper);
        List<BloodSugarBed> records = sugarDepartmentPage.getRecords();
        Iterator<BloodSugarBed> iterator = records.iterator();
        while (iterator.hasNext()){
            BloodSugarBed next = iterator.next();
            QueryWrapper<BloodSugarPatientInfo> query = Wrappers.query();
            query.eq("the_hospital_status","0");
            query.eq("bed_id",next.getId());
            query.eq("department_id",next.getDepartmentId());
            //根据条件查询一条数据，数据库数据混乱时会报错
            /*BloodSugarPatientInfo one = bloodSugarPatientInfoService.getOne(query);
            if (one != null){*/
            //查询数据条数
            int one = bloodSugarPatientInfoService.count(query);
            if (one != 0){
                iterator.remove();
            }
        }
        sugarDepartmentPage.setRecords(records);
        if (sugarBedPage.getTotal() > 0) {
            return Result.ok().data(sugarDepartmentPage.getRecords());
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }
}

